package com.wanna.common.doc.util;

import com.wanna.common.util.QuietlyUtil;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

/**
 * @author wanna
 * @since 2018-11-28
 */
public final class LineUtil {

    /**
     * 以空字符填充
     *
     * @param str    原字符串
     * @param length 长度
     * @return 原字符串以空字符填充后的字符串
     */
    public static String fillBlank(String str, int length) {
        int strSize = str.length();
        if (strSize >= length) {
            return str;
        }

        int size = length - strSize;
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; i < size; i++) {
            builder.append(" ");
        }
        return builder.toString();
    }

    /**
     * json sample to lines
     *
     * @param sample json sample
     * @return json lines
     * @throws IOException exception
     */
    public static List<String> jsonSampleToLines(String sample) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(sample.getBytes())));
        String line;
        List<String> lines = new LinkedList<>();
        try {
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
            return lines;
        } finally {
            QuietlyUtil.close(reader);
        }
    }
}
